package org.zhangsh.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.zhangsh.netty.handler.NewDelimiterDecoder;
import org.zhangsh.netty.handler.NewStringDecoder;
import org.zhangsh.socket.HostInfo;

import java.util.concurrent.TimeUnit;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-26
 */
public class TimerServer {

    public void bind(int port) throws InterruptedException {
        // 配置服务端的NIO组

        // 负责接收请求
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        try{
            // 服务端启动类
            ServerBootstrap server = new ServerBootstrap();

            // 设置线程池
            server.group(bossGroup, workGroup)
                    // 绑定channel
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.ERROR))
                    // 增加处理链
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // TCP粘包、分包
//                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new NewDelimiterDecoder(1024 * 1024,
                                    Unpooled.copiedBuffer("\0".getBytes())));
                            ch.pipeline().addLast(new NewStringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new IdleStateHandler(5, 5, 5, TimeUnit.SECONDS));
//                            ch.pipeline().addLast(new ReadTimeoutHandler(5, TimeUnit.SECONDS));

                            ch.pipeline().addLast(new TimerServerHandler());
                        }
                    });

            // 绑定端口，同步等待成功
            System.out.println(HostInfo.THREAD_NAME + "server start...");
            ChannelFuture sync = server.bind(port).sync();
            //
            sync.channel().closeFuture().sync();
            System.out.println(HostInfo.THREAD_NAME + "server stop...");

        } finally {
            // 优雅关闭线程池
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
    public static void main(String[] args) throws InterruptedException {
        new TimerServer().bind(HostInfo.HOST_PORT);
    }
}
